package com.ishowcode.controller;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@RestController
@RequestMapping("/redis")
public class RedisTestController {
    @Resource
    private RedisTemplate redisTemplate;
    @GetMapping("/t1")
    public  String t1(){
        String result = "秒杀成功";
        Object total = redisTemplate.opsForValue().get("total");
        if (total==null)return "秒杀未开始";
        if ((int)total <= 0) return "已经被抢光了,秒杀结束";
        List<Object> exec = (List<Object>) redisTemplate.execute(new SessionCallback<List<Object>>() {
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.watch("total");
                operations.multi();
                operations.opsForValue().decrement("total");
                UUID uuid = UUID.randomUUID();
                operations.opsForSet().add("Sec_kill_UserID",uuid);
                operations.opsForValue().set("user:"+uuid,"正在登陆");
                return operations.exec();
            }
        });
        Set sec_kill_userID = redisTemplate.opsForSet().members("Sec_kill_UserID");
        if (exec==null||exec.size()==0){
            result = "抢票失败!!";
        }
        return result;
    }
    @GetMapping("/t2")
    public  String t2(){
        redisTemplate.opsForList().leftPush("books","笑傲江湖");
        redisTemplate.opsForList().leftPush("books","java并发编程");
        redisTemplate.opsForList().leftPushAll("books","spring","mysql","springboot");
        List books = redisTemplate.opsForList().range("books", 0, -1);
        String booklist = "";
        for (Object book:books
             ) {
            System.out.println("book->"+book.toString());
            booklist+=book.toString()+"-> ";
        }
        return booklist;
    }
}
